package login

import (
	"encoding/json"
	"fmt"

	"gitee.com/douxuefeng/go-utils/request"
	accessToken "gitee.com/douxuefeng/go-utils/wechat/corp/access_token"
	"gitee.com/douxuefeng/go-utils/wechat/corp/config"
	"gitee.com/douxuefeng/go-utils/wechat/corp/params"
)

type login struct {
	cf *config.CorpConfig
}

const code2SessionUrl string = params.CorpApi + "/miniprogram/jscode2session?access_token=%s&js_code=%s&grant_type=authorization_code"

func NewLogin(cf *config.CorpConfig) *login {
	return &login{
		cf: cf,
	}
}

func (a *login) Code2Session(data *params.LoginRequest) params.LoginReply {
	token, err := accessToken.NewAccessToken(a.cf).GetAccessToken()
	if err != nil {
		return params.LoginReply{
			Errcode: 1,
			Errmsg:  err.Error(),
		}
	}
	url := fmt.Sprintf(code2SessionUrl, token, data.JsCode)
	req := request.NewRequest()
	rsp, err := req.Get(url)
	if err != nil {
		return params.LoginReply{
			Errcode: 1,
			Errmsg:  err.Error(),
		}
	}
	var rs params.LoginReply
	err = json.Unmarshal(rsp.Body(), &rs)
	if err != nil {
		return params.LoginReply{
			Errcode: 1,
			Errmsg:  err.Error(),
		}
	}
	return rs
}
